﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Linq;

namespace DbSharp.Framework.CaseFile.Parser
{
     
    class ResultsetOutputSettingHelper
    {

        public static IResultsetOutputSetting CreateResultsetOutputSetting(XElement resultsetRootElement, DefaultRsOutputSetting defaultRsOutputSetting)
        { 
            var outputArgAttr=resultsetRootElement.Attribute("outputArgument") ;
            if (outputArgAttr==null)
            {
                return defaultRsOutputSetting;
            }

            string outputArgument = outputArgAttr.Value.Trim();
            var resultsetOutputSetting = new ResultsetOutputSetting(defaultRsOutputSetting, outputArgument);
            var outputFieldsSettingElement = resultsetRootElement.Element("outputSetting");
            if (outputFieldsSettingElement != null)
            {
                //override output settings 
                OutputSettingAttrParser.OverrideSetting(resultsetOutputSetting, outputFieldsSettingElement);

                //add output fields
                var q = from fieldItem in outputFieldsSettingElement.Elements("field")
                        let fieldName = fieldItem.Attribute("name").Value.Trim()
                        let outputNameAttr = fieldItem.Attribute("outputName")
                        let nullValuePlaceHolderAttr = fieldItem.Attribute("nullValuePlaceHolder")
                        select new
                        {
                            FieldName = fieldName,
                            OutputFieldName = ((outputNameAttr == null) || (string.IsNullOrEmpty(outputNameAttr.Value.Trim()))) ? fieldName : outputNameAttr.Value.Trim(),
                            NullValuePlaceHolder = (nullValuePlaceHolderAttr == null) ? string.Empty : nullValuePlaceHolderAttr.Value
                        };
                foreach (var item in q)
                {
                    resultsetOutputSetting.AddOutputFieldName(item.FieldName, item.OutputFieldName, item.NullValuePlaceHolder);
                }
            }
            return resultsetOutputSetting;
        }

    }
}
